<template>
	<view class="container">
		<view class="balance-card">
			<view class="balance-title">当前备用余额</view>
			<view class="balance-value">
				<text v-if="currentBalance !== null">¥{{ formatMoney(currentBalance) }}</text>
				<text v-else>--</text>
			</view>
			<view class="balance-desc">
				<text>{{ balanceDesc }}</text>
			</view>
		</view>

		<view class="section-card">
			<view class="section-title">调整类型</view>
			<view class="type-selector">
				<view
					class="type-item"
					:class="{ active: form.type === 'increase' }"
					@click="setAdjustType('increase')"
				>
					<view class="type-icon increase-icon">+</view>
					<view class="type-label">增加</view>
					<view class="type-tip">补充备用金</view>
				</view>
				<view
					class="type-item"
					:class="{ active: form.type === 'decrease' }"
					@click="setAdjustType('decrease')"
				>
					<view class="type-icon decrease-icon">-</view>
					<view class="type-label">减少</view>
					<view class="type-tip">释放备用金</view>
				</view>
			</view>
		</view>

		<view class="section-card">
			<view class="section-header">
				<text class="section-title">调整金额</text>
				<text class="section-extra">单位：元</text>
			</view>
			<input
				class="amount-input"
				type="digit"
				:value="form.amount"
				@input="handleAmountInput"
				placeholder="请输入正数金额，最多两位小数"
			/>
			<view class="input-hint">请确保金额准确，提交后立即生效</view>
		</view>

		<!-- <view class="section-card">
			<view class="section-header">
				<text class="section-title">备注说明</text>
				<text class="section-extra optional">选填，最多50字</text>
			</view>
			<textarea
				class="remark-input"
				v-model="form.remark"
				placeholder="请填写本次调整的原因，例如“补充备用金”或“回收多余备用金”"
				maxlength="50"
				show-confirm-bar="false"
			></textarea>
		</view> -->

		<view class="tips-card">
			<view class="tips-title">操作说明</view>
			<view class="tips-item">1. 调整金额为正数，增加/减少由上方操作类型决定。</view>
			<view class="tips-item">2. 系统会立即更新备用金余额。</view>
			<view class="tips-item">3. 若存在异常，请及时联系财务人员核对。</view>
		</view>

		<view class="submit-container">
			<view
				class="submit-btn"
				:class="{ disabled: submitting }"
				@click="submitAdjust"
			>
				<text class="submit-text">{{ submitting ? '提交中...' : '确认调整' }}</text>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			currentBalance: null,
			lastUpdateTime: '',
			form: {
				type: 'increase',
				amount: '',
				remark: ''
			},
			submitting: false
		}
	},
	computed: {
		balanceDesc() {
			if (this.lastUpdateTime) {
				return `最后更新：${this.lastUpdateTime}`
			}
			return '正在获取备用金余额...'
		}
	},
	onShow() {
		this.loadPettyCashBalance()
	},
	methods: {
		loadPettyCashBalance() {
			this.$u.api.wallet.assetsSummary().then(res => {
				if (res && (res.result == 'true' || res.result === true || res.code === 'true' || res.code === '1') && res.data) {
					const balance = res.data.pettyCashBalance !== undefined ? res.data.pettyCashBalance : res.data.accountBalance
					if (balance !== undefined && balance !== null) {
						this.currentBalance = parseFloat(balance)
						this.lastUpdateTime = this.formatDateTime(new Date())
					}
				}
			}).catch(err => {
				console.error('获取备用金余额失败:', err)
				uni.showToast({
					title: '获取余额失败',
					icon: 'none'
				})
			})
		},
		setAdjustType(type) {
			if (this.form.type !== type) {
				this.form.type = type
			}
		},
		handleAmountInput(e) {
			let value = e.detail.value || ''
			value = value.replace(/[^\d.]/g, '')
			const parts = value.split('.')
			if (parts.length > 2) {
				value = parts[0] + '.' + parts.slice(1).join('')
			}
			if (parts.length === 2 && parts[1].length > 2) {
				value = parts[0] + '.' + parts[1].substring(0, 2)
			}
			this.form.amount = value
		},
		submitAdjust() {
			if (this.submitting) {
				return
			}
			const amount = parseFloat(this.form.amount || 0)
			if (!this.form.amount || isNaN(amount) || amount <= 0) {
				uni.showToast({
					title: '请输入有效的调整金额',
					icon: 'none'
				})
				return
			}
			
			uni.showModal({
				title: '提示',
				content: '确定调整备用金吗？',
				success: (res) => {
					if (res.confirm) {
						this.submitPettyCashAdjust()
					}
				}
			})
		},
		//提交调整备用金
		submitPettyCashAdjust() {
			const amount = parseFloat(this.form.amount || 0)
			const params = {
				amount: amount.toFixed(2),
				type: this.form.type,
				remark: this.form.remark || ''
			}

			this.submitting = true
			uni.showLoading({
				title: '提交中...',
				mask: true
			})

			this.$u.api.wallet.pettyCashAdjust(params).then(res => {
				this.submitting = false
				uni.hideLoading()

				const success = res && (res.result == 'true' || res.result === true || res.code === 'true' || res.code === true || res.code === '1')
				if (success) {
					const data = res.data || {}
					const newBalance = data.newBalance !== undefined ? parseFloat(data.newBalance) : null
					this.currentBalance = newBalance !== null && !isNaN(newBalance)
						? newBalance
						: this.calculateNewBalance(amount)
					this.lastUpdateTime = this.formatDateTime(new Date())
					uni.showToast({
						title: data.message || res.message || '调整成功',
						icon: 'success'
					})
					this.form.amount = ''
					this.form.remark = ''
				} else {
					uni.showToast({
						title: res.message || '调整失败，请稍后重试',
						icon: 'none'
					})
				}
			}).catch(err => {
				this.submitting = false
				uni.hideLoading()
				console.error('备用金调整失败:', err)
				uni.showToast({
					title: '提交失败，请检查网络',
					icon: 'none'
				})
			})
		},
		calculateNewBalance(amount) {
			if (this.currentBalance === null) {
				return amount
			}
			const delta = this.form.type === 'increase' ? amount : -amount
			return parseFloat(this.currentBalance) + delta
		},
		formatMoney(value) {
			if (value === null || value === undefined || value === '') {
				return '0.00'
			}
			return parseFloat(value).toFixed(2)
		},
		formatDateTime(date) {
			const yyyy = date.getFullYear()
			const mm = String(date.getMonth() + 1).padStart(2, '0')
			const dd = String(date.getDate()).padStart(2, '0')
			const hh = String(date.getHours()).padStart(2, '0')
			const mi = String(date.getMinutes()).padStart(2, '0')
			return `${yyyy}-${mm}-${dd} ${hh}:${mi}`
		}
	}
}
</script>

<style scoped>
.container {
	background-color: #f5f6fa;
	min-height: calc(100vh - 120px);
	max-height: calc(100vh - 120px);
	padding: 20rpx 24rpx 140rpx;
	box-sizing: border-box;
}

.balance-card {
	background: linear-gradient(135deg, #5a98ea 0%, #2d6fd6 100%);
	color: #ffffff;
	border-radius: 20rpx;
	padding: 40rpx 32rpx;
	margin-bottom: 24rpx;
	box-shadow: 0 20rpx 30rpx rgba(45, 111, 214, 0.25);
}

.balance-title {
	font-size: 30rpx;
	opacity: 0.85;
	margin-bottom: 16rpx;
}

.balance-value {
	font-size: 60rpx;
	font-weight: bold;
	margin-bottom: 10rpx;
}

.balance-desc {
	font-size: 24rpx;
	opacity: 0.85;
}

.section-card {
	background-color: #ffffff;
	border-radius: 16rpx;
	padding: 30rpx 28rpx;
	margin-bottom: 20rpx;
	box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.04);
}

.section-title {
	font-size: 30rpx;
	color: #1a1a1a;
	font-weight: 600;
}

.section-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 24rpx;
}

.section-extra {
	font-size: 26rpx;
	color: #999999;
}

.optional {
	font-size: 24rpx;
}

.type-selector {
	display: flex;
	gap: 20rpx;
	margin-top: 24rpx;
}

.type-item {
	flex: 1;
	border: 1px solid #e8e8e8;
	border-radius: 20rpx;
	padding: 24rpx;
	text-align: center;
	transition: all 0.2s ease;
}

.type-item.active {
	border-color: #2d6fd6;
	background: rgba(45, 111, 214, 0.08);
	box-shadow: 0 10rpx 20rpx rgba(45, 111, 214, 0.15);
}

.type-icon {
	width: 60rpx;
	height: 60rpx;
	line-height: 60rpx;
	border-radius: 50%;
	margin: 0 auto 10rpx;
	font-size: 36rpx;
	font-weight: bold;
	color: #ffffff;
}

.increase-icon {
	background: #19be6b;
}

.decrease-icon {
	background: #ff4d4f;
}

.type-label {
	font-size: 30rpx;
	font-weight: 600;
	color: #1a1a1a;
	margin-bottom: 6rpx;
}

.type-tip {
	font-size: 24rpx;
	color: #999999;
}

.amount-input {
	width: 100%;
	height: 100rpx;
	border-radius: 16rpx;
	border: 1px solid #e8e8e8;
	padding: 0 24rpx;
	font-size: 36rpx;
	color: #1a1a1a;
	box-sizing: border-box;
}

.amount-input::placeholder {
	color: #bfbfbf;
}

.input-hint {
	font-size: 24rpx;
	color: #999999;
	margin-top: 16rpx;
}

.remark-input {
	width: 100%;
	min-height: 160rpx;
	border: 1px solid #e8e8e8;
	border-radius: 16rpx;
	padding: 20rpx;
	box-sizing: border-box;
	font-size: 28rpx;
	color: #1a1a1a;
	background-color: #fafafa;
}

.tips-card {
	background-color: #fff9ec;
	border-radius: 16rpx;
	padding: 28rpx;
	color: #b27c35;
	margin-bottom: 140rpx;
}

.tips-title {
	font-size: 28rpx;
	font-weight: 600;
	margin-bottom: 16rpx;
}

.tips-item {
	font-size: 24rpx;
	line-height: 1.6;
	margin-bottom: 8rpx;
}

.submit-container {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	padding: 20rpx 40rpx 40rpx;
	background-color: rgba(255, 255, 255, 0.95);
	box-shadow: 0 -6rpx 30rpx rgba(0, 0, 0, 0.06);
}

.submit-btn {
	height: 90rpx;
	background: linear-gradient(135deg, #ff6b6b 0%, #ff4069 100%);
	border-radius: 45rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	box-shadow: 0 12rpx 24rpx rgba(255, 64, 105, 0.35);
}

.submit-btn.disabled {
	opacity: 0.6;
}

.submit-text {
	font-size: 32rpx;
	color: #ffffff;
	font-weight: 600;
}
</style>

